﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Partial Class Control_WhatCookToDay_Detail
    Inherits System.Web.UI.UserControl
    Private strFileUrl As String
    Private strUrlYoutube As String
    Private strPlayerUrl As String
    Private strImageUrl As String
    Private strLinkUrl As String
    Public Property ImageUrl() As String
        Get
            Return strImageUrl
        End Get
        Set(ByVal Value As String)
            strImageUrl = Value
        End Set
    End Property
    Public Property LinkUrl() As String
        Get
            Return strLinkUrl
        End Get
        Set(ByVal Value As String)
            strLinkUrl = Value
        End Set
    End Property
    'System.Configuration.ConfigurationManager.AppSettings("player_url")
    Private strVideoTitle As String

    Public Property UrlYoutube() As String
        Get
            Return strUrlYoutube
        End Get
        Set(ByVal Value As String)
            strUrlYoutube = Value
        End Set
    End Property
    Public Property FileUrl() As String
        Get
            Return strFileUrl
        End Get
        Set(ByVal Value As String)
            strFileUrl = Value
        End Set
    End Property
    Public Property PlayerUrl() As String
        Get
            Return strPlayerUrl
        End Get
        Set(ByVal Value As String)
            strPlayerUrl = Value
        End Set
    End Property
    Public Property VideoTitle() As String
        Get
            Return strVideoTitle
        End Get
        Set(ByVal Value As String)
            strVideoTitle = Value
        End Set
    End Property
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then

            If Not Page.RouteData.Values("id") Is Nothing Then
                'xu ly jquery khi post back
                Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
                If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                    ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquerydetail()", True)
                Else
                    Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquerydetail()", "});"), True)
                End If

                hidID.Value = Page.RouteData.Values("id")
                ShowData()
                '  Comment1.CommentTypeID = Function_Name.Contest
                '  Comment1.TargetID = hidID.Value
            End If
        End If
    End Sub

    Protected Sub ShowData()
        Using data As New VSEntities
            'Add DomainName DUC 09-09-2014
            Dim p As formula = (From q In data.formulae Where q.Domain = DomainName And q.Id = hidID.Value And q.StatusId = 3 Select q).SingleOrDefault

            If Not p Is Nothing Then
                If (Session("PageViewDetail") Is Nothing) Then
                    Session("PageViewDetail") = Now
                    'Update so luot xem len 1
                    p.Viewed = IIf(IsNothing(p.Viewed) = True, 1, p.Viewed + 1)
                    data.SaveChanges()
                Else
                    If (DateDiff(DateInterval.Second, CType(Session("PageViewDetail"), Date), Now()) >= ConfigurationManager.AppSettings("SettingTimeUpdatePageView")) Then
                        'Update so luot xem len 1
                        p.Viewed = IIf(IsNothing(p.Viewed) = True, 1, p.Viewed + 1)
                        data.SaveChanges()
                        Session("PageViewDetail") = Now
                    End If
                End If

                hplTitle.Text = p.FormulaType.Title.ToString
                Page.Title = p.Title & " - " & HeaderTitleSSM
                Page.MetaDescription = p.Description
                ''Facebook Tag
                'Dim metaTagTitle As New HtmlMeta
                'metaTagTitle.Attributes.Add("property", "og:title")
                'metaTagTitle.Attributes.Add("content", p.Title & " - " & HeaderTitleSSM)
                'Page.Header.Controls.RemoveAt(5)
                'Page.Header.Controls.AddAt(5, metaTagTitle)

                'Dim metaTagUrl As New HtmlMeta
                'metaTagUrl.Attributes.Add("property", "og:url")
                'metaTagUrl.Attributes.Add("content", HttpContext.Current.Request.Url.AbsoluteUri)
                'Page.Header.Controls.RemoveAt(7)
                'Page.Header.Controls.AddAt(7, metaTagUrl)

                'Dim metaTagImg As New HtmlMeta
                'metaTagImg.Attributes.Add("property", "og:image")
                'metaTagImg.Attributes.Add("content", p.Image)
                'Page.Header.Controls.RemoveAt(8)
                'Page.Header.Controls.AddAt(8, metaTagImg)

                'Dim metaTagDesc As New HtmlMeta
                'metaTagDesc.Attributes.Add("property", "og:description")
                'metaTagDesc.Attributes.Add("content", p.Description)
                'Page.Header.Controls.RemoveAt(10)
                'Page.Header.Controls.AddAt(10, metaTagDesc)

                'Show keyword
                Dim strKeyWord As String = ""
                'Add DomainName DUC 09-09-2014
                Dim obj = (From ck In data.FormulaKeywords Join k In data.Keywords On ck.KeywordId Equals k.KeywordID Where ck.Domain = DomainName And k.Domain = DomainName And ck.id = p.Id Order By k.Keyword1 Ascending Select New With {.KeyWord = k.Keyword1}).ToList
                For i As Integer = 0 To obj.Count - 1
                    strKeyWord &= obj(i).KeyWord & ";"
                Next
                Page.MetaKeywords = strKeyWord

                ' ltrViewAndUpdateDate.Text = "Ngày cập nhật " & CType(p.PublishedDate, DateTime).ToString("dd.MM.yyyy") '"Lượt xem " & IIf(IsNothing(p.Viewed) = True, 1, p.Viewed) & "<br>

                If (Not p.URL Is Nothing AndAlso p.URL.ToString <> "") Then
                    divVideo.Visible = True
                    If p.IsYoutube = True Then
                        pnlVideoUpload.Visible = False
                        pnlYoutube.Visible = True
                        VideoTitle() = p.Title
                        FileUrl() = SplitVideoYoutube(p.URL)
                        ltrShow.Text = p.URL
                    Else
                        Dim baseUrl As String = Request.Url.GetLeftPart(UriPartial.Authority)
                        VideoTitle() = p.Title
                        PlayerUrl() = baseUrl + ResolveUrl_Video("~/jwplayer/player.swf")
                        FileUrl() = IIf(IsNothing(p.URL) = True, "", p.URL)
                        ImageUrl() = IIf(IsNothing(p.Image) = True, "", p.Image)
                        pnlVideoUpload.Visible = True
                        pnlYoutube.Visible = False
                    End If
                Else
                    divImg.Visible = True
                    imgFormula.ImageUrl = p.Image
                End If

                lblDescription.Text = IIf(IsNothing(p.Description) = True, "", p.Description)
                lblMaterial.Text = IIf(IsNothing(p.Material) = True, "", p.Material)
                lblWaytocook.Text = IIf(IsNothing(p.WayToCook) = True, "", p.WayToCook)
                lblFastconduct.Text = IIf(IsNothing(p.FastConduct) = True, "", p.FastConduct)
                lblPortion.Text = IIf(IsNothing(p.Portion) = True, "", p.Portion & " Người")
                lblTimepreparing.Text = IIf(IsNothing(p.TimePreparing) = True, "", p.TimePreparing & " Phút")
                lblTimetocook.Text = IIf(IsNothing(p.TimeToCook) = True, "", p.TimeToCook & " Phút")
                'If Not p.Cost Is Nothing Then
                '    lblCost.Text = "Giá tiền: " & IIf(IsNothing(p.Cost) = True, "", Format(CType(p.Cost, Double), "#,##0.###") & " vnđ")
                'Else
                '    lblCost.Text = "Giá tiền: "
                'End If

                hidMenuId.Value = p.FormulaTypeId
                ' lblVoted.Text = IIf(IsNothing(p.Voted) = True, "0", p.Voted)
                '   hplFbLike.Attributes.Add("onclick", "return SetVoteFormula('" & hidID.Value & "', '" & lblVoted.ClientID & "')")
                ' lblCountComment.Text = IIf(CountAmountCommentOfObject(p.Id).ToString Is Nothing, "0", CountAmountCommentOfObject(p.Id.ToString).ToString)
            End If

            'Load formula cùng cate
            'Add DomainName DUC 09-09-2014
            Dim qOther = (From f In data.formulae Where f.Domain = DomainName And f.Id <> p.Id And f.FormulaTypeId = p.FormulaTypeId And f.StatusId = 3 And f.PublishedDate <= Now And (f.eEffectiveDate >= Now Or f.eEffectiveDate Is Nothing) Order By f.PublishedDate Descending Select New With {f.Id, f.Title, f.Image, f.QueryString, f.Description, .QueryStringFT = f.FormulaType.QueryString, f.Viewed, f.Voted}).ToList
            Dim iPageSize As Integer = hidPageSize.Value
            '--BEGIN Thiet lap thong so paging sau khi query skip take
            hidCountOther.Value = qOther.Count
            If CInt(hidCountOther.Value) > 0 Then
                Create_PagerOther(hidCountOther.Value, 1, iPageSize, 10)
            Else
                'Div1.Visible = False
            End If
            '--END Thiet lap thong so paging sau khi query skip take

            '--BEGIN paging by skip take
            Dim _resultData = qOther.Skip(0).Take(iPageSize).ToList
            '--END paging by skip take

            With rptContentByCat
                .DataSource = _resultData
                .DataBind()
            End With
        End Using
    End Sub
    Protected Function SplitVideoYoutube(ByVal strUrl As String) As String
        Dim intStart As Integer = strUrl.IndexOf("=")
        Dim intEnd As Integer = strUrl.IndexOf("&")
        Dim scr As String = strUrl.Substring(intStart + 1, strUrl.Length - intStart - 1)
        Return scr
    End Function

    Public Function ResolveUrl_Video(ByVal url As String) As String
        If url Is Nothing Then
            Throw New ArgumentNullException("url", "url can not be null")
        End If
        If url.Length = 0 Then
            Throw New ArgumentException("The url can not be an empty string", "url")
        End If

        ' there is no ~ in the first character position, just return the url 
        If url(0) <> "~"c Then
            Return url
        End If

        Dim applicationPath As String = HttpContext.Current.Request.ApplicationPath

        ' there is just the ~ in the URL, return the applicatonPath 
        If url.Length = 1 Then
            Return applicationPath
        End If

        ' assume url looks like ~somePage 
        Dim indexOfUrl As Integer = 1

        ' determine the middle character 
        Dim midPath As String = If((applicationPath.Length > 1), "/", String.Empty)

        ' if url looks like ~/ or ~\ change the indexOfUrl to 2 
        If url(1) = "/"c OrElse url(1) = "\"c Then
            indexOfUrl = 2
        End If

        Return applicationPath & midPath & url.Substring(indexOfUrl)
    End Function
    Protected Sub rptContentByCat_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptContentByCat.ItemDataBound
        Dim p = CType(e.Item.DataItem, Object)

        Dim imgNews As Image = CType(e.Item.FindControl("imgNews"), Image)
        If (Not p.Image Is Nothing) Then
            imgNews.ImageUrl = p.Image.ToString.Replace("~/Uploads", "")
        End If
        imgNews.ImageAlign = ImageAlign.Middle

        Dim hplNews As HyperLink = CType(e.Item.FindControl("hplNews"), HyperLink)
        hplNews.NavigateUrl = "~/" & Page.RouteData.Values("MenuId") & "-" & strRewriteWhatCookToday & "/" & p.QueryStringFT.ToString & "/" & p.QueryString.ToString & "-" & p.Id.ToString & ".html"
        Dim hplTitle As HyperLink = CType(e.Item.FindControl("hplTitle"), HyperLink)

        If (Not p.Title Is Nothing AndAlso p.Title.ToString <> "") Then
            hplTitle.Text = p.Title.ToString
        Else
            hplTitle.Text = ""
        End If
        hplTitle.NavigateUrl = "~/" & Page.RouteData.Values("MenuId") & "-" & strRewriteWhatCookToday & "/" & p.QueryStringFT.ToString & "/" & p.QueryString.ToString & "-" & p.Id.ToString & ".html"

    

    End Sub

#Region "Cac thu tuc phan trang"
    Sub Create_PagerOther(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndexOther_page.Value = TotalPage
        'gan lai curPage de set active
        hidCurOther_Page.Value = Page_Index
        'generate ra left page
        If TotalPage > 1 And Page_Index <> 1 Then
            lnkFirstOther.Enabled = True
        Else
            lnkFirstOther.Enabled = False
        End If

        If TotalPage > 1 And Page_Index <> TotalPage Then
            lnkLastOther.Enabled = True
        Else
            lnkLastOther.Enabled = False
        End If
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPageOther
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPageOther_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPageOther.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = CType(e.Item.FindControl("lnkTitleOther"), LinkButton)

        'dang ky async ko postback
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)

        If e.Item.DataItem = hidCurOther_Page.Value Then
            lnkTitle.CssClass = "active"
            lnkTitle.Text = e.Item.DataItem
        Else
            '  lnkTitle.CssClass = "pagesLink"
            lnkTitle.Text = e.Item.DataItem
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Sub BindDatabyCate(ByVal iPage As Integer, ByVal iPageSize As Integer)
        Using data As New VSEntities
            'Add DomainName DUC 09-09-2014
            Dim _resultData = (From f In data.formulae Where f.Domain = DomainName And f.Id <> hidID.Value And f.FormulaTypeId = hidMenuId.Value And f.StatusId = 3 And f.PublishedDate <= Now And (f.eEffectiveDate >= Now Or f.eEffectiveDate Is Nothing) Order By f.PublishedDate Descending Select New With {f.Id, f.Title, f.Image, f.QueryString, f.Description, .QueryStringFT = f.FormulaType.QueryString, f.Viewed, f.Voted}).Skip((iPage - 1) * iPageSize).Take(iPageSize).ToList
            hidCurOther_Page.Value = iPage
            Create_PagerOther(hidCountOther.Value, iPage, iPageSize, 10)
            With rptContentByCat
                .DataSource = _resultData
                .DataBind()
            End With
        End Using
    End Sub
    Protected Sub lnkTitleOther_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        'ham bind data - take skip data
        BindDatabyCate(CInt(lnkTile.ToolTip.ToString), CInt(hidPageSize.Value))

    End Sub
    Protected Sub lnkFirstOther_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirstOther.Click

        hidCurOther_Page.Value = hidCurOther_Page.Value - 1

        BindDatabyCate(CInt(hidCurOther_Page.Value), CInt(hidPageSize.Value))
    End Sub
    Protected Sub lnkLastOther_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLastOther.Click
        hidCurOther_Page.Value = hidCurOther_Page.Value + 1
        BindDatabyCate(CInt(hidCurOther_Page.Value), CInt(hidPageSize.Value))
    End Sub
#End Region
End Class
